<template>
  <view class="player-container">
    <!-- 背景模糊图片 -->
    <view class="background-blur" v-if="currentSong">
      <image :src="currentSong.cover_image_url" mode="aspectFill" />
    </view>

    <!-- 播放器内容 -->
    <view class="player-content">
      <!-- 返回按钮 -->
      <view class="back-btn" @click="goBack">
        <text class="back-icon">‹</text>
      </view>

      <!-- 歌曲封面 -->
      <view class="cover-section">
        <view class="cover-container" :class="{ 'rotating': isPlaying }">
          <image 
            class="cover-image" 
            :src="currentSong ? currentSong.cover_image_url : ''" 
            mode="aspectFill"
          />
        </view>
      </view>

      <!-- 歌曲信息 -->
      <view class="song-info" v-if="currentSong">
        <text class="song-name">{{ currentSong.name }}</text>
        <text class="song-artist">{{ currentSong.artist_name }}</text>
      </view>

      <!-- 进度条 -->
      <view class="progress-section">
        <text class="time-text">{{ formatTime(currentTime) }}</text>
        <slider 
          class="progress-slider"
          :value="progressPercent"
          :max="100"
          @change="onProgressChange"
          activeColor="#ff6b6b"
          backgroundColor="#ddd"
          block-size="20"
        />
        <text class="time-text">{{ formatTime(duration) }}</text>
      </view>

      <!-- 控制按钮 -->
      <view class="control-section">
        <view class="control-btn" @click="prevSong">
          <text class="control-icon">⏮️</text>
        </view>
        
        <view class="play-btn" @click="togglePlay">
          <text class="play-icon">{{ isPlaying ? '⏸️' : '▶️' }}</text>
        </view>
        
        <view class="control-btn" @click="nextSong">
          <text class="control-icon">⏭️</text>
        </view>
      </view>

      <!-- 播放模式 -->
      <view class="mode-section">
        <view class="mode-btn" @click="toggleMode">
          <text class="mode-icon">{{ modeIcon }}</text>
        </view>
        
        <view class="favorite-btn" @click="toggleFavorite">
          <text :class="isFavorite ? 'favorite-icon active' : 'favorite-icon'">{{ isFavorite ? '❤️' : '🤍' }}</text>
        </view>
      </view>

      <!-- 播放列表 -->
      <view class="playlist-section" v-if="showPlaylist">
        <view class="playlist-header">
          <text class="playlist-title">播放列表</text>
          <text class="playlist-count">({{ playlist.length }})</text>
        </view>
        
        <scroll-view class="playlist-content" scroll-y="true">
          <view 
            class="playlist-item" 
            v-for="(song, index) in playlist" 
            :key="song.song_id"
            :class="{ 'active': index === currentIndex }"
            @click="playSongByIndex(index)"
          >
            <image class="playlist-cover" :src="song.cover_image_url" mode="aspectFill" />
            <view class="playlist-info">
              <text class="playlist-name">{{ song.name }}</text>
              <text class="playlist-artist">{{ song.artist_name }}</text>
            </view>
            <text class="playlist-status" v-if="index === currentIndex">
              {{ isPlaying ? '♪' : '⏸️' }}
            </text>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
// 内联API配置以避免模块导入问题
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          reject(res.data)
        }
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

// 导入音乐播放器
import musicPlayer from '/utils/musicPlayer.js'

const api = {
  music: {
    addFavorite(songId) {
      return request({
        url: '/music/favorite',
        method: 'POST',
        data: { songId }
      })
    },
    removeFavorite(songId) {
      return request({
        url: `/music/favorite/${songId}`,
        method: 'DELETE'
      })
    },
    getFavorites() {
      return request({
        url: '/music/favorites',
        method: 'GET'
      })
    },
    getSongDetail(songId) {
      return request({
        url: `/music/song/${songId}`,
        method: 'GET'
      })
    }
  }
}

export default {
  data() {
    return {
      currentSong: null,
      isPlaying: false,
      currentTime: 0,
      duration: 0,
      playlist: [],
      currentIndex: 0,
      playMode: 'list', // list, single, random
      isFavorite: false,
      showPlaylist: false
    }
  },

  computed: {
    progressPercent() {
      if (this.duration === 0) return 0
      return (this.currentTime / this.duration) * 100
    },

    modeIcon() {
      const icons = {
        list: '🔁',
        single: '🔂',
        random: '🔀'
      }
      return icons[this.playMode] || '🔁'
    }
  },

  onLoad() {
    this.initPlayer()
  },

  onShow() {
    this.updatePlayerState()
  },

  methods: {
    // 初始化播放器
    initPlayer() {
      // 监听播放器事件
      musicPlayer.on('play', () => {
        this.isPlaying = true
      })
      
      musicPlayer.on('pause', () => {
        this.isPlaying = false
      })
      
      musicPlayer.on('timeUpdate', (data) => {
        this.currentTime = data.currentTime
        this.duration = data.duration
      })
      
      musicPlayer.on('canplay', () => {
        this.duration = musicPlayer.audioContext.duration
      })
      
      musicPlayer.on('error', (error) => {
        console.error('播放器错误:', error)
        uni.showToast({
          title: '播放失败: ' + (error.errMsg || '未知错误'),
          icon: 'none',
          duration: 3000
        })
      })
    },

    // 更新播放器状态
    updatePlayerState() {
      const playerInfo = musicPlayer.getCurrentInfo()
      this.currentSong = playerInfo.song
      this.isPlaying = playerInfo.isPlaying
      this.playlist = playerInfo.playlist
      this.currentIndex = playerInfo.currentIndex
      
      if (this.currentSong) {
        this.checkFavoriteStatus()
      }
    },

    // 检查收藏状态
    async checkFavoriteStatus() {
      if (!this.currentSong) return
      
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          this.isFavorite = false
          return
        }
        
        const res = await api.music.getFavorites()
        // 确保正确处理API返回数据
        const favorites = Array.isArray(res) ? res : (res.data || [])
        this.isFavorite = favorites.some(song => song.song_id === this.currentSong.song_id)
      } catch (error) {
        console.error('检查收藏状态失败:', error)
        uni.showToast({
          title: '获取收藏状态失败',
          icon: 'none'
        })
        this.isFavorite = false
      }
    },

    // 返回
    goBack() {
      uni.navigateBack()
    },

    // 切换播放状态
    togglePlay() {
      musicPlayer.togglePlay()
    },

    // 上一首
    prevSong() {
      musicPlayer.prev()
    },

    // 下一首
    nextSong() {
      musicPlayer.next()
    },

    // 切换播放模式
    toggleMode() {
      const modes = ['list', 'single', 'random']
      const currentIndex = modes.indexOf(this.playMode)
      this.playMode = modes[(currentIndex + 1) % modes.length]
      
      uni.showToast({
        title: `播放模式：${this.getModeText()}`,
        icon: 'none'
      })
    },

    // 获取播放模式文本
    getModeText() {
      const texts = {
        list: '列表循环',
        single: '单曲循环',
        random: '随机播放'
      }
      return texts[this.playMode] || '列表循环'
    },

    // 切换收藏状态
    async toggleFavorite() {
      if (!this.currentSong) return
      
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }

      // 先更新UI状态
      const newFavoriteState = !this.isFavorite
      this.isFavorite = newFavoriteState
      
      try {
        if (newFavoriteState) {
          await api.music.addFavorite(this.currentSong.song_id)
          uni.showToast({
            title: '已添加收藏',
            icon: 'none'
          })
        } else {
          await api.music.removeFavorite(this.currentSong.song_id)
          uni.showToast({
            title: '已取消收藏',
            icon: 'none'
          })
        }
      } catch (error) {
        // 操作失败时恢复状态
        this.isFavorite = !newFavoriteState
        console.error('收藏操作失败:', error)
        uni.showToast({
          title: '操作失败: ' + (error.message || ''),
          icon: 'none'
        })
      }
      
      // 强制视图更新
      this.$forceUpdate()
    },

    // 进度条变化
    onProgressChange(e) {
      const percent = e.detail.value
      const time = (percent / 100) * this.duration
      musicPlayer.seek(time)
    },

    // 格式化时间
    formatTime(seconds) {
      if (!seconds || isNaN(seconds)) return '00:00'
      
      const mins = Math.floor(seconds / 60)
      const secs = Math.floor(seconds % 60)
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
    },

    // 按索引播放歌曲
    playSongByIndex(index) {
      musicPlayer.setPlaylist(this.playlist, index)
    }
  }
}
</script>

<style scoped>
.player-container {
  position: relative;
  height: 100vh;
  background-color: #000;
  overflow: hidden;
}

.background-blur {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  filter: blur(20rpx);
  opacity: 0.3;
}

.background-blur image {
  width: 100%;
  height: 100%;
}

.player-content {
  position: relative;
  z-index: 10;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 40rpx;
  background: linear-gradient(180deg, rgba(0,0,0,0.3) 0%, rgba(0,0,0,0.8) 100%);
}

.back-btn {
  position: absolute;
  top: 40rpx;
  left: 40rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 20;
}

.back-icon {
  font-size: 40rpx;
  color: white;
  font-weight: bold;
}

.cover-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 100rpx;
}

.cover-container {
  width: 500rpx;
  height: 500rpx;
  border-radius: 250rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 40rpx rgba(0, 0, 0, 0.5);
  transition: transform 0.3s ease;
}

.cover-container.rotating {
  animation: rotate 10s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.cover-image {
  width: 100%;
  height: 100%;
}

.song-info {
  text-align: center;
  margin: 60rpx 0;
}

.song-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 20rpx;
}

.song-artist {
  display: block;
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.8);
}

.progress-section {
  display: flex;
  align-items: center;
  margin: 40rpx 0;
}

.time-text {
  font-size: 24rpx;
  color: white;
  min-width: 80rpx;
}

.progress-slider {
  flex: 1;
  margin: 0 20rpx;
}

.control-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
}

.control-btn {
  width: 100rpx;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-icon {
  font-size: 50rpx;
}

.play-btn {
  width: 120rpx;
  height: 120rpx;
  background-color: #ff6b6b;
  border-radius: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 40rpx;
}

.play-icon {
  font-size: 60rpx;
  color: white;
}

.mode-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40rpx;
}

.mode-btn, .favorite-btn {
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 40rpx;
  display: flex;
  margin-bottom: 40rpx;
  align-items: center;
  justify-content: center;
}

.mode-icon {
  font-size: 40rpx;
}

.favorite-icon {
  font-size: 40rpx;
  color: #ff6b6b;
  transition: color 0.3s;
}

.favorite-icon.active {
  color: red !important;
}

.playlist-section {
  position: relative;
  margin-top: 20rpx;
  background-color: rgba(0, 0, 0, 0.7);
  border-radius: 30rpx;
  max-height: 35vh;
  padding-bottom: 20rpx;
  overflow: hidden;
}

.playlist-header {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.playlist-title {
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.playlist-count {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
  margin-left: 10rpx;
}

.playlist-content {
  max-height: 400rpx;
}

.playlist-item {
  display: flex;
  align-items: center;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.playlist-item.active {
  background-color: rgba(255, 107, 107, 0.2);
}

.playlist-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.playlist-info {
  flex: 1;
}

.playlist-name {
  display: block;
  font-size: 28rpx;
  color: white;
  margin-bottom: 5rpx;
}

.playlist-artist {
  display: block;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.6);
}

.playlist-status {
  font-size: 30rpx;
  color: #ff6b6b;
}
</style>
